"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 向for each row类型触发器中导入数据，部分测试点合理报错
Create At   : 2023/06/02
Owner       : n@ningyali
Description :
        1.建表
        2.创建触发器函数
        3.创建触发器
        4.导入合法数据
        5.导入非法数据
        6.清理环境
Expect      :
        1.创建成功
        2.创建成功
        3.创建成功
        4.成功
        5.合理报错
        6.成功
History     :
"""
import os
import unittest

from yat.test import Node

from testcase.COMPATIBILITY.GRAMMAR.LOAD. \
    Opengauss_Compatibility_Grammar_Load_Common import LoadData
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class LoadData0069(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.common = Common()
        self.load_data = LoadData()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.constant = Constant()
        self.case_lable = 'load_data_0069'
        self.db_name = f'db_{self.case_lable}'
        self.t_name = f't_{self.case_lable}'
        self.f_name = f'f_{self.case_lable}'
        self.trigger_name = f'trigger_{self.case_lable}'
        self.file_path = os.path.join('/home', self.pri_user.ssh_user)
        self.cols = 'c_01 int,c_02 char(50)'

        text1 = '----pre_step1：创建数据文件；expect:创建成功----'
        self.log.info(text1)
        self.data1 = "(11,'aasdcdfafadf')(22,虎皮兰虎皮兰)(33,'1绿萝绿萝hg')"
        self.data2 = "(121,虎皮兰虎皮兰)(131,hdt,ys,zt,yst)(141,1658156)"
        res = self.load_data.create_data_file(self.pri_user, self.case_lable,
                                              self.data1, self.data2)
        self.assertTrue(res, '执行失败:' + text1)

        text2 = '-----创建兼容B库；expect:创建成功-----'
        self.log.info(text2)
        res = self.load_data.create_b_db(self.pri_sh, self.db_name)
        self.assertTrue(res, '执行失败:' + text2)

    def test_load(self):
        text = '-----step1：创建表; expect：建表成功-----'
        self.log.info(text)
        res = self.load_data.create_table(self.pri_sh, self.db_name,
                                          self.t_name, self.cols)
        self.assertTrue(res, '执行失败:' + text)

        text = '-----step2：创建触发器函数; expect:创建成功-----'
        self.log.info(text)
        sql = f'''create or replace function {self.f_name}() 
            returns trigger as
            \\$\\$
            declare
            begin
                update {self.t_name} set c_02='test' where c_01=2;
            return new;
            end
            \\$\\$ language plpgsql;'''
        res = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, res,
                      '执行失败:' + text)

        text = '-----step3：创建触发器; expect:创建成功-----'
        self.log.info(text)
        sql = f'drop trigger if exists {self.trigger_name} ' \
            f'on {self.t_name} cascade;' \
            f'create trigger {self.trigger_name} ' \
            f'after insert on {self.t_name}\n' \
            f'for each row execute procedure {self.f_name}();'
        res = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.TRIGGER_CREATE_SUCCESS_MSG, res,
                      '执行失败:' + text)

        text = '-----step4：导入数据，数据格式合法；expect：成功-----'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_1.txt')
        res1 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path,
                                        into_type='', encoding='utf8',
                                        line_start='(', line_end=')')
        rows, _ = self.common.parse_sql_query_res(res1)
        expect = [['11', 'aasdcdfafadf'], ['22', '虎皮兰虎皮兰'],
                  ['33', '1绿萝绿萝hg']]
        self.assertEqual(expect, rows, '执行失败' + text)

        text = '-----step5：导入数据，数据格式非法；expect：合理报错-----'
        self.log.info(text)
        f_path = os.path.join(self.file_path, f'{self.case_lable}_2.txt')
        res2 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path,
                                        into_type='', encoding='utf8',
                                        line_start='(', line_end=')')
        err_info = 'ERROR:  extra data after last expected column'
        self.assertIn(err_info, res2, '执行失败' + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        res = self.load_data.clear_env(self.pri_sh, self.pri_user,
                                       self.db_name,
                                       os.path.join(self.file_path,
                                                    f"{self.case_lable}*"))
        self.assertTrue(res, '执行失败:清理环境')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
